<script setup lang="ts">
import { ref } from 'vue'
import * as mars3d from 'mars3d'
// 声明文件位于 src/types/utils.d.ts
// @ts-ignore
import { toGeoJSON } from "../utils/index";


const importing = ref(false)
const inputRef = ref<HTMLInputElement | null>(null)

function openFile() {
  inputRef.value?.click()
}

interface WaylineFrom {
  Placemark: Array<any>
  positionsArr: number[][]
  takeOffRefPoint: string
  takeOffRefPointAGLHeight: number
  takeOffSecurityHeight: number
  flyToWaylineMode: string
  waylineCoordinateSysParam: { heightMode: 'EGM96' | 'relativeToStartPoint' | 'aboveGroundLevel' }
  globalWaypointTurnMode: string
  autoFlightSpeed: number
  payloadParam: { imageFormat: string }
  globalWaypointHeadingParam: { waypointHeadingMode: string }
  distance?: number
  duration?: number
}

async function onFileChange(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return
  importing.value = true
  try {
    toGeoJSON(file).then(async (data:any) => {

      // 统一提取坐标序列：优先 FeatureCollection 的 LineString；否则回退到 fromKml 的 positionsArr / Placemark
      let coords: any[] | undefined
      if (data && Array.isArray(data.features)) {
        const line = data.features.find((f: any) => f?.geometry?.type === 'LineString')
        if (line) coords = (line.geometry as any).coordinates
      }
      if (!coords && Array.isArray(data?.positionsArr) && data.positionsArr.length > 0) {
        coords = data.positionsArr
      }
      if (!coords && Array.isArray(data?.Placemark) && data.Placemark.length > 0) {
        coords = data.Placemark.map((pm: any) => {
          const [lng, lat, alt] = String(pm?.Point?.coordinates || '').split(',').map((v: string) => Number(v))
          return [lng || 0, lat || 0, alt || 0]
        })
      }
      if (!coords || coords.length === 0) throw new Error('未解析到有效航线坐标')

      // 构造 from 基础结构（参考 goEditRoute 使用字段）
      const from: WaylineFrom = {
        Placemark: [],
        positionsArr: [],
        takeOffRefPoint: '',
        takeOffRefPointAGLHeight: 30,
        takeOffSecurityHeight: 30,
        flyToWaylineMode: 'safely',
        waylineCoordinateSysParam: { heightMode: 'EGM96' },
        globalWaypointTurnMode: 'toPointAndStopWithDiscontinuityCurvature',
        autoFlightSpeed: 5,
        payloadParam: { imageFormat: 'wide,zoom' },
        globalWaypointHeadingParam: { waypointHeadingMode: 'followWayline' },
      }

      // 生成 Placemark 与 positionsArr（Z 作为 EGM96 高度）
      from.positionsArr = coords.map((pos) => {
        const lng = Number((pos as any)[0] ?? 0)
        const lat = Number((pos as any)[1] ?? 0)
        const alt = Number((pos as any)[2] ?? 0)
        return [lng, lat, alt] as [number, number, number]
      })
      from.Placemark = from.positionsArr.map((p, index) => ({
        Point: { coordinates: `${p[0]},${p[1]},${p[2]}` },
        index: String(index),
        useGlobalHeight: '1',
        height: p[2],
        waypointTurnParam: { waypointTurnMode: 'toPointAndStopWithDiscontinuityCurvature', waypointTurnDampingDist: '0.2' },
        waypointSpeed: String(from.autoFlightSpeed),
        actionGroup: [],
      }))

      // 设置起飞点：用首点地形高度作为参考
      const map: mars3d.Map = (window as any).map
      if (!map) throw new Error('地图未初始化')
      const first = from.positionsArr[0]!
      const takeoffGround = await mars3d.PointUtil.getSurfaceHeight(map.scene, [first[0], first[1]] as any).then(r => r.height)
      from.takeOffRefPoint = `${first[1]},${first[0]},${takeoffGround}`

      // 按 heightMode 调整 Z（参考 goEditRoute）
      if (from.waylineCoordinateSysParam.heightMode === 'aboveGroundLevel') {
        for (let i = 0; i < from.positionsArr.length; i++) {
          const p = from.positionsArr[i] as [number, number, number] | undefined
          if (!p) continue
          const [lng, lat] = p
          const ground = await mars3d.PointUtil.getSurfaceHeight(map.scene, [lng, lat] as any).then(r => r.height)
          const pointHeight = Number((from.Placemark[i] as any)?.height) || 0
          p[2] = ground + pointHeight
          from.positionsArr[i] = p
        }
      } else if (from.waylineCoordinateSysParam.heightMode === 'relativeToStartPoint') {
        const qfd = from.takeOffRefPoint.split(',').map(v => Number(v)) as [number, number, number]
        for (let i = 0; i < from.positionsArr.length; i++) {
          const p = from.positionsArr[i] as [number, number, number] | undefined
          if (!p) continue
          const pointHeight = Number((from.Placemark[i] as any)?.height) || 0
          p[2] = Number(qfd[2] ?? 0) + Number(from.takeOffRefPointAGLHeight ?? 0) + pointHeight
          from.positionsArr[i] = p
        }
      } else {
        // EGM96：直接使用点的高度
        for (let i = 0; i < from.positionsArr.length; i++) {
          const p = from.positionsArr[i] as [number, number, number] | undefined
          if (!p) continue
          const pointHeight = Number((from.Placemark[i] as any)?.height) || 0
          p[2] = pointHeight
          from.positionsArr[i] = p
        }
      }

      // 渲染到图层，保存本地（与 goEditRoute 逻辑对齐）
      const layer: mars3d.layer.GraphicLayer = (window as any).graphicLayer
      if (layer) {
        layer.clear()
        // 点
        from.positionsArr.forEach((pos, idx) => {
          const [lng, lat, alt] = pos as [number, number, number]
          new mars3d.graphic.PointEntity({
            position: [lng, lat, alt],
            attr: { name: `航点${idx + 1}`, index: idx },
            style: { color: '#00ffff', pixelSize: 10, clampToGround: false },
          }).addTo(layer)
        })
        // 线
        const line = new mars3d.graphic.PolylineEntity({
          positions: from.positionsArr,
          name: 'road',
          style: { width: 3, color: '#1a9850' },
        })
        layer.addGraphic(line)
        line.flyTo()
        ;(from as any).distance = line.distance
      }

      // 保存当前航线
      localStorage.setItem('wayLine', JSON.stringify(from))
      // 保存到列表
      const listRaw = localStorage.getItem('wayLineList')
      const list = listRaw ? JSON.parse(listRaw) : []
      const id = `${Date.now()}`
      const name = (file as any).name || '未命名航线'
      list.unshift({ id, name, createdAt: Date.now() })
      localStorage.setItem('wayLineList', JSON.stringify(list))
      localStorage.setItem(`wayLine:${id}`, JSON.stringify(from))
      // 通知列表刷新
      window.dispatchEvent(new CustomEvent('wayLineList:updated'))
    })
  } finally {
    importing.value = false
    ;(e.target as HTMLInputElement).value = ''
  }
}
</script>

<template>
  <div class="kmz-importer">
    <input ref="inputRef" type="file" accept=".kmz" style="display:none" @change="onFileChange" />
    <button :disabled="importing" @click="openFile">{{ importing ? '解析中...' : '导入KMZ' }}</button>
  </div>
</template>

<style scoped>
.kmz-importer { position: absolute; z-index: 20; top: 10px; right: 10px; }
button { padding: 6px 10px; }
</style>


